package com.hqyj.realm;

import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired(required = false)
    UserMapper userMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object userName = principals.fromRealm(this.getName()).iterator().next();
        //查询用户编号
        int sysId = userMapper.selectIdByUserName(userName+"");
        //根据用户名查询用户参数
        List<String> list = userMapper.selectPermissionByName(userName + "");
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        if (list.size() > 0) {
            //添加权限
            sai.addStringPermissions(list);
        }

        return sai;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //取出用户名
        UsernamePasswordToken to =(UsernamePasswordToken)token;
        String userName = to.getPrincipal()+"";
        //验证用户名输入是否正确
        List<User> list =userMapper.selectByName(userName);
        if(list.size()==0){
            throw new UnknownAccountException();
        }
        //创建凭证
        AuthenticationInfo au = new SimpleAuthenticationInfo(
                list.get(0).getSysName(),//用户名
                list.get(0).getSysPwd(),//密码
                new Md5Hash(list.get(0).getSalt()),//加密算法和盐值
                this.getName()//myrealm对象
        );
        return au;
    }
}
